package com.baiwei.vpnapi.utils;

import com.baiwei.vpnapi.dao.UserMapper;
import com.baiwei.vpnapi.entity.VpnUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.time.Instant;
import java.util.Date;
import java.util.Map;

/**
 * @program: vpnapi
 * @description: JWT 工具类
 * @author: Mr. Stone
 * @create: 2020-02-25 01:10
 **/
@Component
public class JwtTokenUtil implements Serializable {

    @Autowired
    private UserMapper userMapper;

    private static final long serialVersionUID = -2550185165626007488L;

    /*
     * 超时时间 毫秒 （一个月）
     * */
    public static final long JWT_TTOKEN_VALIDITY =  2592000000L;

    /*
     * JWT 密码
     * */
    @Value("${jwt.secret}")
    private String secret;

    /*
     * 签发 JWT
     * */
    public String doGenerateToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(Instant.now().toEpochMilli()))
                .setExpiration(new Date(Instant.now().toEpochMilli() + JWT_TTOKEN_VALIDITY))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /*
     * 验证token是否过期
     * */
    public boolean isTokenExpired(String token) {
        Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    /*
     * 获取 token username
     * */
    public String getUsernameFromToken(String token) {
        String username = getClaimsFromToken(token).getSubject();
        return username;
    }

    // 从token中获取用户信息
    public VpnUser getVpnUser(String token) {
        String userId = getUsernameFromToken(token);
        VpnUser user = userMapper.selectById(userId);
        return user;
    }
    // 从token中获取专属服务器信息
    public String[] getServerId(String token) {
        Claims claimsFromToken = getClaimsFromToken(token);
        String server = (String)claimsFromToken.get("server");
        if(server != null) {
            return server.split(",");
            //return Integer.valueOf(server);
        }
        return null;
    }



    /*
     * 获取 token 过期时间
     * */
    public Date getExpirationDateFromToken(String token) {
        Date expiration = getClaimsFromToken(token).getExpiration();
        return expiration;
    }

    /*
     * 解析token
     * */
    private Claims getClaimsFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        return claims;
    }

}
